package com.horsecoder.im.common.handler;

import com.horsecoder.common.error.Assert;
import com.horsecoder.im.common.protocol.action.handler.ActionDispatcherHandler;
import com.horsecoder.im.common.protocol.action.handler.Handler;
import com.horsecoder.im.common.protocol.context.SessionSocketHolder;
import com.horsecoder.im.common.protocol.context.chain.request.Request;
import com.horsecoder.im.common.protocol.context.chain.response.Response;
import com.horsecoder.im.common.protocol.context.http.FullRequestContext;
import com.horsecoder.im.common.protocol.context.http.FullResponseContext;
import com.horsecoder.im.common.protocol.convert.Converter;
import com.horsecoder.im.common.protocol.convert.RequestConverter;
import com.horsecoder.im.common.protocol.convert.ResponseConverter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import org.springframework.util.StringUtils;

/**
 * Http协议输入解码Handler
 * <p>
 * Author: Zhu yuhan
 * Email: zhuyuhan2333@qq.com
 * Date: 2022/3/16 11:11 上午
 **/
public class HorsecoderImServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final Converter<FullRequestContext, Request> requestConverter = new RequestConverter();

    private final Converter<Response, FullResponseContext> responseConverter = new ResponseConverter();

    private final Handler dispatch = new ActionDispatcherHandler();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
        FullRequestContext fullRequestContext = new FullRequestContext(channelHandlerContext, fullHttpRequest);
        Request request = requestConverter.convert(fullRequestContext);
        Response response = new Response(request);
        String identity = request.getIdentity();
        String receiver = request.getReceiver();
        Assert.isTrue(!StringUtils.isEmpty(identity) && !StringUtils.isEmpty(receiver), "IDENTITY_ERROR");
        SessionSocketHolder.putSocketChannel(identity, channelHandlerContext.channel());
        dispatch.handle(SessionSocketHolder.getSocketChannel(receiver), request, response);
    }
}
